package day19.zhiyou100;


// 测试类
class TestTicket {

    public static void main(String[] args) {
        // 构建共享对象
        Ticket ticket = new Ticket(10,0);
        // 构建分线程
        TicketWindow w1 = new TicketWindow(ticket,"窗口一");
        TicketWindow w2 = new TicketWindow(ticket,"窗口二");
        TicketWindow w3 = new TicketWindow(ticket,"窗口三");
        w1.start();
        w2.start();
        w3.start();
    }
}

// 卖票窗口 线程
class TicketWindow extends Thread {

    public TicketWindow(Ticket ticket,String name) {
        super(name);
        this.ticket = ticket;
    }

    private Ticket ticket;
    // 重写run方
    @Override
    public void run() {
        ticket.saleTicket();
    }

}

public class Ticket {
    // 总共票的数量
    private int num;// 100-->num--
    private int sum;// 已经购买第几张票

    // 卖票的功能
    public void saleTicket() {
        while (true) {
            synchronized (this) {
                // num > 0
                if (num <= 0) {
                    break;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                num--;
                sum++;
                System.out.println(Thread.currentThread().getName() + "购买了第" + sum + "张票,还剩余" + num + "张票");
            }
        }
    }

    public Ticket() {
    }

    public Ticket(int num,int sum) {
        this.num = num;
        this.sum = sum;
    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public int getSum() {
        return sum;
    }

    public void setSum(int sum) {
        this.sum = sum;
    }
}
